package com.zp.drug.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.common.core.constant.BaseConstants;
import com.zp.common.core.constant.CacheNames;
import com.zp.common.core.constant.DrugConstants;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.common.redis.utils.CacheUtils;
import com.zp.common.satoken.utils.LoginHelper;
import com.zp.drug.api.vo.DrugInfoVo;
import com.zp.drug.entity.DrugStockAllLog;
import com.zp.drug.entity.DrugStorageDept;
import com.zp.drug.entity.DrugSupplierCata;
import com.zp.drug.entity.bo.*;
import com.zp.drug.entity.vo.DrugClassDictVo;
import com.zp.drug.entity.vo.DrugStockAllLogParamVo;
import com.zp.drug.entity.vo.DrugStockAllLogVo;
import com.zp.drug.mapper.DrugStockAllLogMapper;
import com.zp.drug.mapper.DrugSupplierCataMapper;
import com.zp.drug.service.IDrugStockAllLogService;
import com.zp.system.api.entity.SysDept;
import com.zp.system.api.entity.SysDictData;
import com.zp.system.api.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 药品库存流转记录Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-10-31
 */
@RequiredArgsConstructor
@Service
public class DrugStockAllLogServiceImpl implements IDrugStockAllLogService {

    private final DrugStockAllLogMapper baseMapper;

    private final DrugSupplierCataMapper drugSupplierCataMapper;

    // 药品分类
    static List<SysDictData> DRUG_CLASSIFICATION_DICT_MAP = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.DRUG_CLASSIFICATION);
    // 药品剂型
    static List<SysDictData> DRUG_FORM_DICT_MAP = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.DRUG_FORM_DICT);
    // 规格单位
    static List<SysDictData> SPEC_UNIT_MAP = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.SPEC_UNIT);
    // 药品出入库方式：建账、正常等
    static List<SysDictData> DRUG_STORAGE_TYPE_MAP = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.DRUG_STORAGE_TYPE);
    // 药品功效类别 （呼吸系统药物、呼吸系统药物）
    static Map<String, DrugClassDictVo> DRUG_CLASS_DICT_MAP = CacheUtils.get(CacheNames.DRUG_CLASS_DICT);
    // 药品库存单位
    static Map<String, DrugStorageDept> DRUG_STORAGE_DEPT_MAP = CacheUtils.get(CacheNames.DRUG_STORAGE_DEPT);
    //         // 获取厂商、生产商信息
    static Map<String, DrugSupplierCata> DRUG_SUPPLIER_CATA_MAP = CacheUtils.get(CacheNames.DRUG_SUPPLIER_CATA);
    // 药品基本信息
    static Map<String, DrugInfoVo> DRUG_INFO_VO_MAP = CacheUtils.get(CacheNames.DRUG_INFO);

    static List<SysDictData> STOCK_CONSUME_TYPE_MAP = CacheUtils.get(CacheNames.SYS_DICT, CacheNames.STOCK_CONSUME_TYPE);

    /**
     * 用户信息
     */
    static Map<String, SysUser> SYS_USER_MAP = CacheUtils.get(CacheNames.SYS_USER);

    static Map<String, SysDept> SYS_DEPT_MAP = CacheUtils.get(CacheNames.SYS_DEPT);


    /**
     * 查询药品库存流转记录
     */
    @Override
    public DrugStockAllLogVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询药品库存流转记录列表(分页)
     */
    @Override
    public TableDataInfo<DrugStockAllLogVo> queryPageList(DrugStockAllLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DrugStockAllLog> lqw = buildQueryWrapper(bo);
        Page<DrugStockAllLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询药品库存流转记录列表(不分页)
     */
    @Override
    public List<DrugStockAllLogVo> queryList(DrugStockAllLogBo bo) {
        LambdaQueryWrapper<DrugStockAllLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrugStockAllLog> buildQueryWrapper(DrugStockAllLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DrugStockAllLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getClinicNo()), DrugStockAllLog::getClinicNo, bo.getClinicNo());
        lqw.eq(StringUtils.isNotBlank(bo.getHospitalNo()), DrugStockAllLog::getHospitalNo, bo.getHospitalNo());
        lqw.eq(StringUtils.isNotBlank(bo.getDocumentNo()), DrugStockAllLog::getDocumentNo, bo.getDocumentNo());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordType()), DrugStockAllLog::getRecordType, bo.getRecordType());
        lqw.eq(StringUtils.isNotBlank(bo.getSourceType()), DrugStockAllLog::getSourceType, bo.getSourceType());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugInfoId()), DrugStockAllLog::getDrugInfoId, bo.getDrugInfoId());
        lqw.eq(StringUtils.isNotBlank(bo.getStockId()), DrugStockAllLog::getStockId, bo.getStockId());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugType()), DrugStockAllLog::getDrugType, bo.getDrugType());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugFrom()), DrugStockAllLog::getDrugFrom, bo.getDrugFrom());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugClass()), DrugStockAllLog::getDrugClass, bo.getDrugClass());
        lqw.like(StringUtils.isNotBlank(bo.getDrugName()), DrugStockAllLog::getDrugName, bo.getDrugName());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugCode()), DrugStockAllLog::getDrugCode, bo.getDrugCode());
        lqw.eq(StringUtils.isNotBlank(bo.getSysDrugCode()), DrugStockAllLog::getSysDrugCode, bo.getSysDrugCode());
        lqw.eq(StringUtils.isNotBlank(bo.getDrugInput()), DrugStockAllLog::getDrugInput, bo.getDrugInput());
        lqw.eq(StringUtils.isNotBlank(bo.getSpec()), DrugStockAllLog::getSpec, bo.getSpec());
        lqw.eq(StringUtils.isNotBlank(bo.getUnits()), DrugStockAllLog::getUnits, bo.getUnits());
        lqw.like(StringUtils.isNotBlank(bo.getFirmName()), DrugStockAllLog::getFirmName, bo.getFirmName());
        lqw.eq(bo.getPackageNum() != null, DrugStockAllLog::getPackageNum, bo.getPackageNum());
        lqw.eq(StringUtils.isNotBlank(bo.getPriceId()), DrugStockAllLog::getPriceId, bo.getPriceId());
        lqw.eq(StringUtils.isNotBlank(bo.getPackSize()), DrugStockAllLog::getPackSize, bo.getPackSize());
        lqw.eq(bo.getAmount() != null, DrugStockAllLog::getAmount, bo.getAmount());
        lqw.eq(bo.getCurrentAmount() != null, DrugStockAllLog::getCurrentAmount, bo.getCurrentAmount());
        lqw.eq(bo.getItemPrice() != null, DrugStockAllLog::getItemPrice, bo.getItemPrice());
        lqw.eq(bo.getTradePrice() != null, DrugStockAllLog::getTradePrice, bo.getTradePrice());
        lqw.eq(bo.getNetworkPrice() != null, DrugStockAllLog::getNetworkPrice, bo.getNetworkPrice());
        lqw.eq(bo.getCosts() != null, DrugStockAllLog::getCosts, bo.getCosts());
        lqw.eq(bo.getPriceQuotiety() != null, DrugStockAllLog::getPriceQuotiety, bo.getPriceQuotiety());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyDept()), DrugStockAllLog::getApplyDept, bo.getApplyDept());
        lqw.eq(StringUtils.isNotBlank(bo.getApplyPerson()), DrugStockAllLog::getApplyPerson, bo.getApplyPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordDept()), DrugStockAllLog::getRecordDept, bo.getRecordDept());
        lqw.eq(StringUtils.isNotBlank(bo.getRecordPerson()), DrugStockAllLog::getRecordPerson, bo.getRecordPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getUsePerson()), DrugStockAllLog::getUsePerson, bo.getUsePerson());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), DrugStockAllLog::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), DrugStockAllLog::getRemarks, bo.getRemarks());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
                DrugStockAllLog::getCreateTime, DateUtils.dateTime(params.get("beginTime")), DateUtils.dateTime(params.get("endTime")));
        lqw.orderByDesc(DrugStockAllLog::getCreateTime);
        return lqw;
    }

    /**
     * 新增药品库存流转记录
     */
    @Override
    public Boolean insertByBo(DrugStockAllLogBo bo) {
        DrugStockAllLog add = BeanUtil.toBean(bo, DrugStockAllLog.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean save(DrugStockBo bo) {
        return Boolean.FALSE;
    }

    /**
     * 组织库存表基本数据
     *
     * @param detailBo
     * @param bo
     * @return
     */
    private static DrugStockBo getDrugStockBo(DrugExportDetailBo detailBo, DrugExportMasterBo bo) {
        DrugStockBo drugStockBo = new DrugStockBo();
        drugStockBo.setRecordType(bo.getRecordType());
        drugStockBo.setDrugPriceId(detailBo.getDrugPriceId());
        drugStockBo.setPackSize(detailBo.getPackSize());
        drugStockBo.setId(detailBo.getStockId());
        drugStockBo.setMinUnits(detailBo.getMinUnits());
        drugStockBo.setMinSpec(detailBo.getMinSpec());
        drugStockBo.setPackageSpec(detailBo.getPackageSpec());
        drugStockBo.setPackageUnits(detailBo.getPackageUnits());
        return drugStockBo;
    }

    /**
     * 根据RecordType进行数据分类
     *
     * @param bo
     */
    @Override
    @Transactional
    public Boolean caseRecordTypeSave(DrugStockAllLogParamVo bo) {
        Boolean type = false;
        switch (bo.getRecordType()) {
            case DrugConstants.ONE:
                // 门诊发药
                type = saveClinicGrant(bo);
                break;
            case DrugConstants.TWO:
                // 住院处方
                break;
            case DrugConstants.THREE:
                // 摆药
                break;
            case DrugConstants.FOUR:
                // 住院退药
                break;
            case DrugConstants.FIVE:
                // 入库
                type = saveDrugImportMaster(bo);
                break;
            case DrugConstants.SIX:
                // 出库
                type = saveDrugExportMaster(bo);
                break;
            case DrugConstants.SEVEN:
                // 盘盈入库
                break;
            case DrugConstants.EIGHT:
                // 科室扣减
                break;
            case DrugConstants.NINE:
                // 门诊处方退药
                break;
            case DrugConstants.TEN:
                // 手术室用药（药房发药）
                break;
            case DrugConstants.ELEVEN:
                // 盘亏出库
                type = saveClinicGrant(bo);
                break;
            default:
                break;

        }
        return type;
    }

    /**
     * 入库
     *
     * @param drugStockAllLogParamVo
     * @return
     */
    @Transactional
    public Boolean saveDrugImportMaster(DrugStockAllLogParamVo drugStockAllLogParamVo) {
        DrugImportMasterBo bo = drugStockAllLogParamVo.getDrugImportMasterBo();
        List<DrugStockAllLog> logList = new ArrayList<>();
        List<DrugStockBo> drugStockBoList = bo.getStockBoList();
        for (DrugStockBo dsItem : drugStockBoList) {
            // 获取当前药品info信息
            DrugInfoVo drugInfoVo = dsItem.getDrugInfoVo();
            // 获取当前药品入库药品明细
            DrugImportDetailBo drugImportDetailBo = dsItem.getDrugImportDetailBo();
            DrugStockAllLog drugStockAllLog = new DrugStockAllLog();
            drugStockAllLog.setDocumentNo(bo.getDocumentNo());
            drugStockAllLog.setPackageNum(drugImportDetailBo.getPackageNum());
            // 组织基础信息
            tissusAllBasicInfo(drugStockAllLog, dsItem);
            drugStockAllLog.setAmount(drugImportDetailBo.getQuantity());
            if (CollectionUtils.isNotEmpty(DRUG_STORAGE_TYPE_MAP)) {
                drugStockAllLog.setSourceType(DRUG_STORAGE_TYPE_MAP.stream()
                        .filter(i -> StringUtils.equals(bo.getImportClass(), i.getDictValue()))
                        .findAny().get().getDictLabel());
            }
            // 调用从drugInfoVo中获取数据 函数
            tissueToDrugInfo(drugStockAllLog, drugInfoVo);
            BigDecimal costs = null;
            if (StringUtils.equals(dsItem.getPackSize(), BaseConstants.IS_SMALL_PACK)) {
                // 进货价
                drugStockAllLog.setTradePrice(drugImportDetailBo.getTradePriceMin());
                // 单价
                drugStockAllLog.setItemPrice(drugImportDetailBo.getRetailPriceMin());
                costs = drugStockAllLog.getItemPrice().multiply(BigDecimal.valueOf(drugStockAllLog.getAmount()));
            } else {
                // 进货价
                drugStockAllLog.setTradePrice(drugImportDetailBo.getTradePrice());
                // 单价
                drugStockAllLog.setItemPrice(drugImportDetailBo.getRetailPrice());
                //大包装
                costs = drugStockAllLog.getItemPrice().multiply(BigDecimal.valueOf(drugStockAllLog.getAmount()));
            }
            drugStockAllLog.setCosts(costs);
            // 登陆人
            String nickName = LoginHelper.getLoginUser().getNickName();
            // 申请科室(领取科室)
            String applyDept = StringUtils.isNotBlank(bo.getStorageId()) && ObjectUtil.isNotNull(DRUG_STORAGE_DEPT_MAP.get(bo.getStorageId()))
                    ? DRUG_STORAGE_DEPT_MAP.get(bo.getStorageId()).getStorageName() : "";
            //记录科室(发放科室)
            String recordDept = "";
            // 记录科室(发放科室)
            String storageFrom = StringUtils.isNotBlank(bo.getStorageFrom()) && ObjectUtil.isNotNull(DRUG_STORAGE_DEPT_MAP.get(bo.getStorageFrom()))
                    ? DRUG_STORAGE_DEPT_MAP.get(bo.getStorageFrom()).getStorageName() : bo.getSupplier();
            // 入库（采购、制剂、建账） 这几种类型 现行库存设置为0
            if (StringUtils.equals(bo.getImportClass(), DrugConstants.DRUG_STORAGE_TYPE.PREPARATION)
                    || StringUtils.equals(bo.getImportClass(), DrugConstants.DRUG_STORAGE_TYPE.PURCHASE)
                    || StringUtils.equals(bo.getImportClass(), DrugConstants.DRUG_STORAGE_TYPE.SET_UP_ACCOUNTS)) {
                drugStockAllLog.setCurrentAmount(0);
                if (StringUtils.equals(bo.getImportClass(), DrugConstants.DRUG_STORAGE_TYPE.PURCHASE)) {
                    recordDept = StringUtils.isNotBlank(bo.getSupplier()) && ObjectUtil.isNotNull(DRUG_SUPPLIER_CATA_MAP.get(bo.getSupplier()))
                            ? DRUG_SUPPLIER_CATA_MAP.get(bo.getSupplier()).getSupplierName() : "";
                } else {
                    recordDept = storageFrom;
                }
            } else {
                drugStockAllLog.setCurrentAmount(dsItem.getQuantity());
                recordDept = storageFrom;
            }

            drugStockAllLog.setPriceQuotiety(BigDecimal.valueOf(1));
            // 组织用户科室信息
            tissusUserInfo(drugStockAllLog, applyDept, nickName, recordDept);
            drugStockAllLog.initEntity();
            drugStockAllLog.setOrgId(LoginHelper.getLoginUser().getOrgId());
            logList.add(drugStockAllLog);
        }
        baseMapper.insertBatch(logList);
        return Boolean.TRUE;
    }

    /**
     * 出库
     *
     * @param drugStockAllLogParamVo
     * @return
     */
    public Boolean saveDrugExportMaster(DrugStockAllLogParamVo drugStockAllLogParamVo) {
        // 获取出库主记录
        DrugExportMasterBo bo = drugStockAllLogParamVo.getDrugExportMasterBo();
        List<DrugStockAllLog> logList = new ArrayList<>();
        // 获取出库药品明细list
        List<DrugExportDetailBo> drugExportDetailBoList = bo.getDetailListSave();
        for (DrugExportDetailBo detailBo : drugExportDetailBoList) {
            // 获取当前药品info信息
            DrugInfoVo drugInfoVo = ObjectUtil.isNotNull(DRUG_INFO_VO_MAP.get(detailBo.getDrugInfoId())) ?
                    DRUG_INFO_VO_MAP.get(detailBo.getDrugInfoId()) : null;
            DrugStockAllLog drugStockAllLog = new DrugStockAllLog();
            drugStockAllLog.setDocumentNo(bo.getDocumentNo());
            drugStockAllLog.setPackageNum(detailBo.getPackageNum());
            // 组织库存表基本数据
            bo.setRecordType(drugStockAllLogParamVo.getRecordType());
            DrugStockBo drugStockBo = getDrugStockBo(detailBo, bo);
            // 组织基础信息
            tissusAllBasicInfo(drugStockAllLog, drugStockBo);
            drugStockAllLog.setAmount(detailBo.getQuantity());
            if (CollectionUtils.isNotEmpty(DRUG_STORAGE_TYPE_MAP)) {
                drugStockAllLog.setSourceType(DRUG_STORAGE_TYPE_MAP.stream()
                        .filter(i -> StringUtils.equals(bo.getExportClass(), i.getDictValue()))
                        .findAny().get().getDictLabel());
            }
            // 调用从drugInfoVo中获取数据 函数
            if (drugInfoVo != null) {
                tissueToDrugInfo(drugStockAllLog, drugInfoVo);
            }
            BigDecimal costs = null;
            if (StringUtils.equals(detailBo.getPackSize(), BaseConstants.IS_SMALL_PACK)) {
                // 进货价
                drugStockAllLog.setTradePrice(detailBo.getTradePriceMin());
                // 单价
                drugStockAllLog.setItemPrice(detailBo.getRetailPriceMin());
                costs = drugStockAllLog.getItemPrice().multiply(BigDecimal.valueOf(drugStockAllLog.getAmount()));
            } else {
                // 进货价
                drugStockAllLog.setTradePrice(detailBo.getPurchasePrice());
                // 单价
                drugStockAllLog.setItemPrice(detailBo.getRetailPrice());
                //大包装
                costs = drugStockAllLog.getItemPrice().multiply(BigDecimal.valueOf(drugStockAllLog.getAmount()));
            }
            drugStockAllLog.setCosts(costs);
            // 登陆人
            String nickName = LoginHelper.getLoginUser().getNickName();
            // 申请科室(领取科室)
            String applyDept = StringUtils.isNotBlank(bo.getReceiverId()) && ObjectUtil.isNotNull(DRUG_STORAGE_DEPT_MAP.get(bo.getReceiverId()))
                    ? DRUG_STORAGE_DEPT_MAP.get(bo.getReceiverId()).getStorageName() : "";
            // 记录科室(发放科室)
            String storageFrom = StringUtils.isNotBlank(bo.getStorageId()) && ObjectUtil.isNotNull(DRUG_STORAGE_DEPT_MAP.get(bo.getStorageId()))
                    ? DRUG_STORAGE_DEPT_MAP.get(bo.getStorageId()).getStorageName() : "";
            drugStockAllLog.setCurrentAmount(0);
            drugStockAllLog.setCurrentAmount(detailBo.getQuantity());
            drugStockAllLog.setPriceQuotiety(BigDecimal.valueOf(1));
            // 组织用户科室信息
            tissusUserInfo(drugStockAllLog, applyDept, nickName, storageFrom);
            drugStockAllLog.initEntity();
            drugStockAllLog.setOrgId(LoginHelper.getLoginUser().getOrgId());
            logList.add(drugStockAllLog);
        }
        baseMapper.insertBatch(logList);
        return Boolean.TRUE;
    }

    public void tissusAllBasicInfo(DrugStockAllLog drugStockAllLog, DrugStockBo dsItem) {
        drugStockAllLog.setRecordType(dsItem.getRecordType());
        if (CollectionUtils.isNotEmpty(STOCK_CONSUME_TYPE_MAP)) {
            drugStockAllLog.setRecordType(STOCK_CONSUME_TYPE_MAP.stream()
                    .filter(i -> StringUtils.equals(drugStockAllLog.getRecordType(), i.getDictValue()))
                    .findAny().get().getDictLabel());
        }
        drugStockAllLog.setPriceId(dsItem.getDrugPriceId());
        drugStockAllLog.setPackSize(dsItem.getPackSize());
        drugStockAllLog.setStockId(dsItem.getId());
        if (StringUtils.equals(dsItem.getPackSize(), BaseConstants.IS_SMALL_PACK)) {
            drugStockAllLog.setSpec(dsItem.getMinSpec());
            if (CollectionUtils.isNotEmpty(SPEC_UNIT_MAP)) {
                drugStockAllLog.setUnits(SPEC_UNIT_MAP.stream()
                        .filter(i -> StringUtils.equals(dsItem.getMinUnits(), i.getDictValue()))
                        .findAny().get().getDictLabel());
            }
        } else {
            drugStockAllLog.setSpec(dsItem.getPackageSpec());
            if (CollectionUtils.isNotEmpty(SPEC_UNIT_MAP)) {
                drugStockAllLog.setUnits(SPEC_UNIT_MAP.stream()
                        .filter(i -> StringUtils.equals(dsItem.getPackageUnits(), i.getDictValue()))
                        .findAny().get().getDictLabel());
            }
        }
    }

    @Transactional
    public Boolean saveClinicGrant(DrugStockAllLogParamVo drugStockAllLogParamVo) {

        DrugStockAllLog drugStockAllLog = drugStockAllLogParamVo.getDrugStockAllLog();
        // 获取当前药品info信息
        DrugInfoVo drugInfoVo = ObjectUtil.isNotNull(DRUG_INFO_VO_MAP.get(drugStockAllLog.getDrugInfoId())) ?
                DRUG_INFO_VO_MAP.get(drugStockAllLog.getDrugInfoId()) : null;
        if (drugInfoVo != null) {
            tissueToDrugInfo(drugStockAllLog, drugInfoVo);
        }
        drugStockAllLog.setUnits(SPEC_UNIT_MAP.stream()
                .filter(i -> StringUtils.equals(drugStockAllLog.getUnits(), i.getDictValue()))
                .findAny().get().getDictLabel());

        if (CollectionUtils.isNotEmpty(DRUG_STORAGE_TYPE_MAP)) {
            drugStockAllLog.setSourceType(DRUG_STORAGE_TYPE_MAP.stream()
                    .filter(i -> StringUtils.equals(drugStockAllLog.getSourceType(), i.getDictValue()))
                    .findAny().get().getDictLabel());
        }
        if (CollectionUtils.isNotEmpty(STOCK_CONSUME_TYPE_MAP)) {
            drugStockAllLog.setRecordType(STOCK_CONSUME_TYPE_MAP.stream()
                    .filter(i -> StringUtils.equals(drugStockAllLog.getRecordType(), i.getDictValue()))
                    .findAny().get().getDictLabel());
        }
        drugStockAllLog.setApplyPerson(ObjectUtil.isNotNull(SYS_USER_MAP) && StringUtils.isNotBlank(drugStockAllLog.getApplyPerson()) ? SYS_USER_MAP.get(drugStockAllLog.getApplyPerson()).getNickName() : "");
        drugStockAllLog.setApplyDept(ObjectUtil.isNotNull(SYS_DEPT_MAP) ? SYS_DEPT_MAP.get(drugStockAllLog.getApplyDept()).getDeptName() : "");
        drugStockAllLog.setRecordPerson(ObjectUtil.isNotNull(SYS_USER_MAP) ? SYS_USER_MAP.get(drugStockAllLog.getRecordPerson()).getNickName() : "");
        drugStockAllLog.setRecordDept(ObjectUtil.isNotNull(SYS_DEPT_MAP) ? SYS_DEPT_MAP.get(drugStockAllLog.getRecordDept()).getDeptName() : "");
        return baseMapper.insert(drugStockAllLog) > 0;
    }

    /**
     * 组织用户科室信息
     *
     * @param drugStockAllLog
     * @param applyDept       请科室(领取科室)
     * @param nickName        申请人(领取人) 领用人
     * @param recordDept      记录科室(发放科室)
     */
    public void tissusUserInfo(DrugStockAllLog drugStockAllLog, String applyDept, String nickName, String recordDept) {
        // 申请科室(领取科室)
        drugStockAllLog.setApplyDept(applyDept);
        // 申请人(领取人)
        drugStockAllLog.setApplyPerson(nickName);
        //记录科室(发放科室)
        drugStockAllLog.setRecordDept(recordDept);
        // 记录人(发放人)
        drugStockAllLog.setRecordPerson(nickName);
        // 领用人
        drugStockAllLog.setUsePerson(nickName);
    }

    /**
     * 从drugInfoVo中获取数据
     *
     * @param drugInfoVo 药品基本信息
     */
    public void tissueToDrugInfo(DrugStockAllLog drugStockAllLog, DrugInfoVo drugInfoVo) {
        drugStockAllLog.setDrugInfoId(drugInfoVo.getId());
        drugStockAllLog.setDrugType(ObjectUtil.isNotNull(DRUG_CLASS_DICT_MAP.get(drugInfoVo.getDrugType()))
                ? DRUG_CLASS_DICT_MAP.get(drugInfoVo.getDrugType()).getClassName() : "");
        if (CollectionUtils.isNotEmpty(DRUG_FORM_DICT_MAP)) {
            drugStockAllLog.setDrugFrom(DRUG_FORM_DICT_MAP.stream()
                    .filter(i -> StringUtils.equals(drugInfoVo.getDrugFrom(), i.getDictValue()))
                    .findAny().get().getDictLabel());
        }
        if (CollectionUtils.isNotEmpty(DRUG_CLASSIFICATION_DICT_MAP)) {
            drugStockAllLog.setDrugClass(DRUG_CLASSIFICATION_DICT_MAP.stream()
                    .filter(i -> StringUtils.equals(drugInfoVo.getDrugClass(), i.getDictValue()))
                    .findAny().get().getDictLabel());
        }
        drugStockAllLog.setDrugName(drugInfoVo.getDrugName());
        drugStockAllLog.setDrugCode(drugInfoVo.getDrugCode());
        drugStockAllLog.setDrugInput(drugInfoVo.getDrugInput());
        drugStockAllLog.setFirmName(drugInfoVo.getFirmName());
    }

    /**
     * 修改药品库存流转记录
     */
    @Override
    public Boolean updateByBo(DrugStockAllLogBo bo) {
        DrugStockAllLog update = BeanUtil.toBean(bo, DrugStockAllLog.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DrugStockAllLog entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除药品库存流转记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
